package com.jmgd.cjlx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jmgd.cjlx.constants.MainConstant;
import com.jmgd.cjlx.service.WdzTokenService;
import com.ovopark.sdk.openplatform.GwInitRequestHandler;
import com.ovopark.sdk.openplatform.core.OvoParkHttpClient;
import org.springframework.stereotype.Service;

@Service
public class WdzTokenServiceImpl implements WdzTokenService {

    @Override
    public String getToken() {
        String resultFlag;
        String token;

        GwInitRequestHandler requestHandler = new GwInitRequestHandler();
        requestHandler.init();
        // 设置业务请求参数
        requestHandler.setParameter("userName", MainConstant.wdz_user);
        requestHandler.setParameter("password", MainConstant.wdz_pwd);

        String function = "open.shopweb.security.mobileLogin";
        String version = "v1";
        String resContent = "";

        //初始化 配置密匙密钥
        //GwInitRequestHandler requestHandler = new GwInitRequestHandler();
        //requestHandler.init();
        // 设置_aid，值为应用id
        requestHandler.setParameter("_aid", MainConstant.wdz_aid);
        requestHandler.setApplicationKey(MainConstant.wdz_akey);
        requestHandler.setApplicationSecret(MainConstant.wdz_asid);

        // 设置需要调用的方法名、请求地址、版本号
        requestHandler.setMethod(function);
        requestHandler.setGateUrl(MainConstant.wdz_apigwUrl);
        requestHandler.setParameter("_version", version);


        // 初始化httpClient
        OvoParkHttpClient httpClient = new OvoParkHttpClient();

        //获取请求带参数的url
        String requestUrl = requestHandler.getRequestURL();

        //设置请求内容
        httpClient.setReqContent(requestUrl);
        System.out.println(requestUrl);
        if (httpClient.call()) {
            resContent = httpClient.getResContent();
            System.out.println(resContent);
        }

        JSONObject jsonObjectParent = JSON.parseObject(resContent);
        resultFlag = jsonObjectParent.get("result").toString();
        if(resultFlag.equals("成功")) {
            token = ((JSONObject) jsonObjectParent.get("data")).get("token").toString();
            return token;
        }
        return null;
    }

}
